<?php
namespace addons\service\library;

use app\api\model\service\MiniTemplate;
use app\api\model\service\ProjectConfigure;
use think\Cache;

class MiniSms
{
    protected $reqUrl = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=';
    protected $accessUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=';
    protected $userAppid ;
    protected $userSecret;
    public function __construct()
    {
        $serviceConfig = ProjectConfigure::getProjectConfig();
        $this->userAppid = $serviceConfig['userappid'];
        $this->userSecret = $serviceConfig['usersecret'];
        $this->skillAppid = $serviceConfig['skillappid'];
        $this->skillSecret = $serviceConfig['skillsecret'];
        $this->shopAppid = $serviceConfig['shopappid'];
        $this->shopSecret = $serviceConfig['shopsecret'];
    }


    /**
     * @param $touser
     * @param $template_id
     * @param $order_address
     * @param $order_type
     * @param $time
     * @param $order_status
     * @param $orer_remarks
     * @return bool|string
     */
    public function sendMessage($params)
    {
        switch ($params['type'])
        {
            case 0:
                $appid = $this->userAppid;
                $appsecret = $this->userSecret;

                break;
            case 1:
                $appid = $this->skillAppid;
                $appsecret = $this->skillSecret;
                break;
            case 2:
                $appid = $this->shopAppid;
                $appsecret = $this->shopSecret;
                break;
        }
        $access_token = $this->getAccessToken($appid,$appsecret,$params['type']);
        $urls = $this->reqUrl. $access_token;
        $data = [];
        $data['touser'] = $params['openid'];
        $templateConfig = MiniTemplate::getTemplateConfig($params['templateAttr']);
        if(empty($templateConfig['template_id']))
        {
            return true;
        }
        $data['template_id'] = $templateConfig['template_id'];
        //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
        $data['page'] = $templateConfig['url'].$params['id'];
        $data['data'] = MiniTemplate::spellParams($params);
        $data['miniprogram_state'] = '';
        self::curlPost($urls,json_encode($data));

        return true;
    }

    private function getAccessToken($appid,$secret,$type)
    {
        switch ($type)
        {
            case 0:
                $key = 'user_wx_access_token';
                break;
            case 1:
                $key = 'skill_wx_access_token';
                break;
            case 2:
                $key = 'shop_wx_access_token';
                break;
            default :
                $key = 'user_wx_access_token';
        }
        $token = Cache::get($key);
        if(!$token)
        {
            $url = $this->accessUrl . $appid . '&secret=' . $secret;
            $res = json_decode(file_get_contents($url), true);
            $token = $res['access_token'];
            Cache::set($key,$token,7000);
        }
        return $token;

    }



//发送post请求
    protected static function curlPost($url,$data)
    {
        $ch = curl_init();
        $params[CURLOPT_URL] = $url;    //请求url地址
        $params[CURLOPT_HEADER] = FALSE; //是否返回响应头信息
        $params[CURLOPT_SSL_VERIFYPEER] = false;
        $params[CURLOPT_SSL_VERIFYHOST] = false;
        $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
        $params[CURLOPT_POST] = true;
        $params[CURLOPT_POSTFIELDS] = $data;
        curl_setopt_array($ch, $params); //传入curl参数
        $content = curl_exec($ch); //执行
        curl_close($ch); //关闭连接
        return $content;
    }


}
